package bean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet(name = "MakeRegister",urlPatterns = "/MakeRegister")
public class MakeRegister extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        makeRegister(request,response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    protected  void makeRegister(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
    {
        String username=request.getParameter("name");
        String passwd=request.getParameter("passwd");
        String email=request.getParameter("email");
        String passwd2=request.getParameter("passwd2");

        if(!function.register_check(username,email,passwd,passwd2))
        {
            response.sendRedirect("/error.jsp");
        }
        else {
            try {
                File file = new File("person.txt");
                BufferedReader input = new BufferedReader(new FileReader(file));

                if (function.ifExit(input,username,email)) {
                    BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
                    function.writeToUser(output,username,email,passwd);
                    output.close();
                    response.sendRedirect("/register_success.jsp");
                } else {
                    response.sendRedirect("/error.jsp");
                }
            } catch (Exception e) {
                System.out.println("读取文件失败！！");
                response.sendRedirect("/error.jsp");
            }
        }

    }
}
